import {
  createRouter,
  createMemoryHistory,
  createWebHistory,
} from 'vue-router'
import store from './store'

// Auto generates routes from vue files under ./pages
// https://vitejs.dev/guide/features.html#glob-import
const pages = import.meta.glob('./pages/*/*.page.vue')

const routes = Object.keys(pages).map((path) => {
  const name = path.match(/\.\/pages(.*)\.page\.vue$/)[1].toLowerCase()
  return {
    path: name === '/home' ? '/' : name,
    // () => import('./pages/*.vue')
    component: pages[path],
  }
})

const router = createRouter({
  // import.meta.env.SSR is injected by Vite.
  history: import.meta.env.SSR ? createMemoryHistory() : createWebHistory(),
  routes,
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
})

router.beforeEach((to, from, next) => {
  if (!['/account/login', '/account/register', '/account/forget'].includes(to.path) && !store?.state?.user?.userId) {
    next({ path: '/account/login' })
    return
  }
  next()
})

export default router
